package com.ttxs.fileformathandling.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.ttxs.fileformathandling.common.ErrorCode;
import com.ttxs.fileformathandling.exception.BusinessException;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer;

import java.io.*;
import java.util.List;
import java.util.Map;


/**
 * YAML 工具类   格式转换、格式验证、格式化功能
 *
 * @author hz
 */
public class YamlUtils {

    private static void begin(String url) {
        if (!yamlValidator(url)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "YAML文件格式错误");
        }
    }


    /**
     * yaml转换json
     *
     * @param yamlFilePath:yaml文件路径
     * @return 返回转换后json格式的字符
     */
    public static String yaml2Json(String yamlFilePath) {
        begin(yamlFilePath);
        // 创建 SnakeYAML 解析器和 Jackson ObjectMapper
        Yaml yaml = new Yaml(new Constructor());
        ObjectMapper objectMapper = new ObjectMapper();

        // 从文件中读取 YAML
        Object yamlObject = null;
        try (FileReader reader = new FileReader(yamlFilePath)) {
            yamlObject = yaml.load(reader);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "YAML文件加载失败");
        }
        // 转换为 JSON
        ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();
        String jsonString = null;
        try {
            jsonString = jsonWriter.writeValueAsString(yamlObject);
        } catch (JsonProcessingException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "YAML转换失败");

        }
        return jsonString;
    }


    /**
     * yaml转换csv
     *
     * @param yamlFilePath: yaml文件路径
     * @return 返回转换后csv格式的字符
     */
    public static String yaml2Csv(String yamlFilePath) {
        begin(yamlFilePath);
        String yamlString = FileUtils.readFileToString(yamlFilePath, "UTF-8");

        Yaml yaml = new Yaml();
        //csv文件特性所在
        List<Map<String, Object>> yamlData = yaml.load(new StringReader(yamlString));
        //保存表头
        StringBuilder csvTab = new StringBuilder();
        //保存数据
        StringBuilder csvData = new StringBuilder();
        int flag = 1;
        for (Map<String, Object> yamlMap : yamlData) {
            for (Map.Entry<String, Object> entry : yamlMap.entrySet()) {
                if (flag == 1) {
                    csvTab.append(entry.getKey()).append(",");
                }
                if (entry.getValue() instanceof List) {
                    //不大可能用到  根据csv特性而言
//                    System.out.println("一对多");
                } else {
                    csvData.append(entry.getValue()).append(",");
                }
            }
            flag = 0;
            csvData.deleteCharAt(csvData.length() - 1);
            csvData.append("\n");
        }
        csvTab.deleteCharAt(csvTab.length() - 1);
        csvTab.append("\n");
        return csvTab.append(csvData).toString();
    }


    /**
     * yaml转换xml
     *
     * @param yamlFilePath:yaml文件路径
     * @return 返回转换后xml格式的字符
     */
    public static String yaml2Xml(String yamlFilePath, String root) {
        begin(yamlFilePath);
        String jsonString = yaml2Json(yamlFilePath);
        return JsonUtils.json2Xml(jsonString, root);
    }


    /**
     * yaml格式化
     *
     * @param filePath：yaml文件路径
     * @return 返回格式化后字符
     */
    public static String yamlFormatter(String filePath) {
        begin(filePath);
        String yamlString = FileUtils.readFileToString(filePath, "UTF-8");
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // 设置块风格，以保持缩进和换行
        options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
        options.setPrettyFlow(true);
        options.setIndent(2); // 设置缩进为2个空格

        // 创建 YAML 解析器和格式化选项
        Yaml yaml = new Yaml(options);

        // 格式化 YAML 代码
        return yaml.dump(yaml.load(yamlString));
    }


    /**
     * yaml格式验证
     *
     * @param filePath yaml文件路径
     */
    public static boolean yamlValidator(String filePath) {
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            Yaml yaml = new Yaml();
            yaml.load(fileInputStream);
            return true;
        } catch (FileNotFoundException | YAMLException e) {
            return false;
        }
    }
}